﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace TeamDev.JQuery.Internals
{
  internal static class InternalUtils
  {
    internal static string ExtractData(object data)
    {
      StringBuilder builder = new StringBuilder();
      builder.Append("{");

      if (data != null)
      {
        bool firstrow = true;
        foreach (PropertyInfo info in data.GetType().GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
        {
          if (!firstrow)
            builder.Append(",");

          object value = info.GetValue(data, null);

          if (string.IsNullOrEmpty((value ?? string.Empty).ToString()))
          {
            builder.AppendFormat("{0}:null", info.Name);
          }
          else
          {
            builder.AppendFormat("{0}:{1}", info.Name,
                                            value.ToString().StartsWith("@") ?
                                                value.ToString().Substring(1) :
                                                string.Format("\'{0}\'", value.ToString()));
          }

          firstrow = false;
        }
      }

      builder.Append("}");
      return builder.ToString();
    }
  }
}
